var defaultPartIcon = "../img/defaultPart.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.53884704455731;//120.206354450751;
var centerY = 29.7219072675705;//30.0725834699399;
var currentGraphic;
var drawHandler;
var dynamicTowPointFiveD;
var extendScal=10;

require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct" ], function(Map, Color, Graphic, InfoTemplate,
		SpatialReference, HeatmapRenderer, OverviewMap, Scalebar, Measurement,
		Units, TDTLayer, TDTAnnoLayer, TDT_ImgLayer, TDT_ImgAnnoLayer,
		GraphicsLayer, ArcGISDynamicMapServiceLayer,
		ArcGISTiledMapServiceLayer, FeatureLayer, Point, Polyline, Polygon,
		Circle, TextSymbol, SimpleMarkerSymbol, PictureMarkerSymbol,
		SimpleLineSymbol, SimpleFillSymbol, Font, LabelClass, Query, QueryTask,
		Draw, Popup, PopupTemplate, dom, domConstruct) {
	// 创建popup弹出层
	/*var popup = new Popup({
		fillSymbol : new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
				new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([
						255, 0, 0 ]), 2), new Color([ 255, 255, 0, 0.25 ]))
	}, domConstruct.create("div"));*/

	// var pt = new Point(xloc, yloc, map.spatialReference);
	map = new Map("map", {
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 17,
		minZoom : 8/*,
		infoWindow : popup*/
	});
	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});

	// 显示比例尺
	scalebar.show();
	// DCI.map2dTool.InitTool(map);
	drawHandler = Draw;
	var vec = new TDTLayer();// 切片线画图
	var veca = new TDTAnnoLayer();// 切片标注
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);

	dynamicTowPointFiveD = new ArcGISTiledMapServiceLayer(arcGisUrl
			+ "/arcgis/rest/services/YuelaiMap/MapServer");
	dynamicTowPointFiveD.hide();
	dynamicTowPointFiveD.id = "dynamicTowPointFiveD";
	map.addLayer(dynamicTowPointFiveD);

	/*
	 * map.addLayer(img); map.addLayer(imga);
	 */

	/*
	 * var url = arcGisUrl + "/arcgis/rest/services/ceshi1/MapServer"; var
	 * part=new FeatureLayer(url+"/part",{ outFields:["*"], maxScale:0,
	 * minScale:4508.935440959931, visible:true, id:"part" });
	 * map.addLayer(part);
	 */

	
	  /*url = arcGisUrl + "/arcgis/rest/services/CZbujian1/MapServer"; 
	  partLayer =new FeatureLayer(url + "/5", { outFields : [ "*" ], maxScale : 0,
	  minScale : 4508.935440959931, visible : true, id : "partLayer" });
	  map.addLayer(partLayer);

	
	 map.graphics.on("click", function(evt){ var attr=evt.graphic.attributes;
	 //message(evt.layerX+":"+evt.layerY);
	 });*/
	 

	// 街道路灯点击事件
	/*
	 * partLayer.on("click", function(evt) { var attr = evt.graphic.attributes;
	 * message(evt.layerX + ":" + evt.layerY + ":" + attr.OBJECTID);
	 * console.log(attr);
	 */
	/*
	 * jQuery("#lightModal").modal("show");
	 * jQuery("#lightX").text(attr.latitude);
	 * jQuery("#lightY").text(attr.longitude);
	 * jQuery("#lightBelonging").text(attr.belonging);
	 * jQuery("#lightManufacturer").text(attr.manufacturer);
	 * jQuery("#lightstatus").text(attr.status);
	 * jQuery("#lighttime").text(attr.garantee_time);
	 */
	// });
	/*map.graphics.on("mouse-over", function(e) {
		console.log("graphicslayer:mouse-over");
		var detailInfo = '图形: ' + e.graphic.geometry.type + '<br>'
		map.infoWindow.setTitle('图形信息');
		map.infoWindow.setContent(detailInfo);

		var taxParcelTemplate = new InfoTemplate("管点信息", "编号: ");
		e.graphic.setInfoTemplate(taxParcelTemplate);

		map.infoWindow.setFeatures(e.graphic);
		map.infoWindow.show(e.graphic.geometry);
	});*/
	/*map.graphics.on("mouse-out", function(e) {
		console.log("graphicslayer:mouse-over");
		map.infoWindow.hide();
	});*/

	map.graphics.on("mouse-down", function(evt) {
		console.log("graphicslayer:mouse-down");
		if (evt.graphic) {
			currentGraphic = evt.graphic;
		}
		if (currentGraphic) {
			currentGraphic.isMouseDown = true;

			map.disableMapNavigation();
			map.disablePan();
		}
	});
	map.on("mouse-drag", function(evt) {
		console.log("map:mouse-drag");
		if (currentGraphic) {
			if (currentGraphic.isMouseDown) {
				currentGraphic.setGeometry(evt.mapPoint);
			}
		}

	});

	map.on("mouse-up", function(evt) {
		console.log("map:mouse-up");
		if (currentGraphic) {
			map.enableMapNavigation();
			map.enablePan();
			currentGraphic.isMouseDown = false;
			EditMapPoint(evt);
		}

	});

	// dojo.connect(map.graphics, "onClick", EditMapPoint);
	toolbar = new Draw(map);
	// initToolbar();
	dojo.connect(toolbar, "onDrawEnd", addToMap);
	map.graphics.setMaxScale(0);
	map.graphics.setMinScale(4508.935440959931);
	/*
	 * var layer = new
	 * ArcGISDynamicMapServiceLayer("https://localhost:6080/arcgis/rest/services/Test/ft/MapServer");
	 * map.addLayer(layer); //用于操作的要素图层，注意我们是操作的宿舍楼图层 var featureLayer = new
	 * FeatureLayer("https://localhost:6080/arcgis/rest/services/Test/ft/FeatureServer/1", {
	 * mode:FeatureLayer.MODE_SNAPSHOT, outFields: ["*"] });
	 * //在添加要素时，利用Draw工具获得geometry对象 var d = new Draw(map, { showTooltips: true
	 * }); //要操作的graphic var g; query("button").on("click",function(event){ var
	 * value=event.rangeParent.data; switch(value){ case "添加要素":
	 * d.activate(Draw.POLYGON); break; case "删除要素":
	 * //创建Graphic对象，删除OBJECTID为34的元素， //因为OBJECTID是主键，所以只需要指定主键即可 g=new
	 * Graphic("","",{ "OBJECTID":34 }); //创建删除对象 var de=new Delete({
	 * "featureLayer":featureLayer, "deletedGraphics":[g] }); //执行删除结果
	 * de.performRedo(); //刷新图层 layer.refresh(); break; case "修改要素":
	 * //用于修改要素的函数,查询更新为36的要素 updateFeature(1); break; case "查询要素":
	 * //用于查询要素的函数，查询主键为36的要素 searchFeather(1); break; } });
	 */
});
$("body").on("#info", "click", function(evt) {
	if (evt.target.id === "info") {
		return;
	}
	var tool = evt.target.id.toLowerCase();
	map.disableMapNavigation();
	toolbar.activate(tool);
});
// 初始化工具栏
function initToolbar() {
	toolbar = new Draw(map);
	toolbar.on("draw-end", addGraphic);

	on(dom.byId("info"), "click", function(evt) {
		if (evt.target.id === "info") {
			return;
		}
		var tool = evt.target.id.toLowerCase();
		map.disableMapNavigation();
		tb.activate(tool);
	});
}
// 添加图形
function addGraphic(evt) {
	tb.deactivate();
	map.enableMapNavigation();

	var symbol;
	if (evt.geometry.type === "point" || evt.geometry.type === "multipoint") {
		symbol = markerSymbol;
	} else if (evt.geometry.type === "line" || evt.geometry.type === "polyline") {
		symbol = lineSymbol;
	} else {
		symbol = fillSymbol;
	}

	evt.geometry.setCacheValue("geoShape", evt.geometry.type);

	gl.add(new Graphic(evt.geometry, symbol));
}
function EditMapPoint(evt) {

	/* message(evt.layerX+":"+evt.layerY); */
	// message(evt.graphic.geometry.x + ":" + evt.graphic.geometry.y);
	if (evt.graphic) {
		var attr = evt.graphic.attributes;
		editPartFromMap(attr, evt.graphic.geometry.x, evt.graphic.geometry.y);
	}
	
	
}
function editPartFromMap(data, x, y) {
	if (!data)
		return;
	setPartLocation(y,x);
	jQuery('#id').val(data.id);
	jQuery('#longitude').val(x);
	jQuery('#latitude').val(y);
	jQuery('#partName').val(data.partName);
	jQuery('#manufacturer').val(data.manufacturer);
	jQuery('#productionTime').val(
			moment(data.productionTime).format('YYYY-MM-DD'));
	jQuery('#installationTime').val(
			moment(data.installationTime).format('YYYY-MM-DD'));
	jQuery('#state').val(data.state.id);
	var iconAddress = data.iconAddress;
	if (typeof (iconAddress) != 'undefined' && iconAddress != '') {
		iconAddress = window.rootPath + '/' + iconAddress;
	} else {
		iconAddress = '../img/upload.png';
	}
	$("#avatar").attr('src', iconAddress);

	jQuery('#deviceIdentify').val(data.deviceIdentify);
	jQuery('#interfaceAddress').val(data.interfaceAddress);
	jQuery('#interfacePort').val(data.interfacePort);

	//jQuery('#Modal').modal('show');
	$("#Modal").modal({
		backdrop : 'static'
	});
};

function addToMap(geometry) {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelPartInMapBtn").attr("disabled", true);
	$(".addPartInMapBtn").attr("disabled", false);

	$('body').css('cursor', 'default');
	map.setMapCursor('default');

	map.showZoomSlider(); // 在地图上显示的缩放滑块
	// 判断几何图形的类型
	switch (geometry.type) {
	case "point":

		/*
		 * var symbol = new esri.symbol.SimpleMarkerSymbol(
		 * esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE, //
		 * 样式,STYLE_CIRCLE(●),STYLE_CROSS(+),STYLE_DIAMOND(◆),STYLE_SQUARE(■),STYLE_X(X)
		 * 10, // 像素 new esri.symbol.SimpleLineSymbol(
		 * esri.symbol.SimpleLineSymbol.STYLE_SOLID, //
		 * 样式,STYLE_DASH(破折号),STYLE_DASHDOT(点划线),STYLE_DASHDOTDOT,STYLE_DOT(点),STYLE_NULL,STYLE_SOLID(实线)
		 * new dojo.Color([ 255, 0, 0 ]), // 颜色 1 // 像素 ), new dojo.Color([ 0,
		 * 255, 0, 0.25 ]) // 颜色和透明度 ); );
		 */

		var symbolurl = getIconForSelectNode();
		var symbol = new esri.symbol.PictureMarkerSymbol({
			"url" : symbolurl, // 图标路径
			"width" : 20, // 图标的宽度
			"height" : 20
		// 图标的高度
		});
		break;
	case "polyline":
		var symbol = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([ 255,
						0, 0 ]), 1);
		break;
	case "polygon":
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;
	case "extent":
		var symbol = new esri.symbol.SimpleFillSymbol(
				esri.symbol.SimpleFillSymbol.STYLE_SOLID,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_DASHDOT,
						new dojo.Color([ 255, 0, 0 ]), 2), new dojo.Color([
						255, 255, 0, 0.25 ]));
		break;
	case "multipoint":
		var symbol = new esri.symbol.SimpleMarkerSymbol(
				esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND, 20,
				new esri.symbol.SimpleLineSymbol(
						esri.symbol.SimpleLineSymbol.STYLE_SOLID,
						new dojo.Color([ 0, 0, 0 ]), 1), new dojo.Color([ 255,
						255, 0, 0.5 ]));
		break;
	}
	var graphic = new esri.Graphic(geometry, symbol);
	map.graphics.add(graphic); // 将绘图加入到图层中
	currentGraphic = graphic;
	// 打开部件基础信息窗口

	jQuery('#id').val('');

	$("#modalForm")[0].reset();

	$("#interfaceForm")[0].reset();

	var file = $("#file")
	file.after(file.clone().val(""));
	file.remove();

	$("#avatar").attr('src', '../img/upload.png');
	$("#longitude").val(geometry.x);
	$("#latitude").val(geometry.y);
	//jQuery('#Modal').modal('show');
	$("#Modal").modal({
		backdrop : 'static'
	});
};
// 地图取消添加网格
jQuery('.cancelPartInMapBtn').on('click', function() {
	toolbar.deactivate(); // 关闭工具栏并激活地图导航.
	$(".cancelPartInMapBtn").attr("disabled", true);
	$(".addPartInMapBtn").attr("disabled", false);
	$('body').css('cursor', 'default');
	map.setMapCursor('default');
});
// 显示2.5D地图
jQuery('.showThreeDInMapBtn').on('click', function() {
	if (dynamicTowPointFiveD) {
		if ($(".showThreeDInMapBtn").html() == "2.5D展示") {
			dynamicTowPointFiveD.show();
			$(".showThreeDInMapBtn").html("2.5D隐藏");
		} else {
			dynamicTowPointFiveD.hide();
			$(".showThreeDInMapBtn").html("2.5D展示");
		}

	}
});
// 添加菜单，弹出弹窗
jQuery('.addPartInMapBtn').on('click', function() {
	var selectNodeId = getTreeIdForSelectNode();
	if (selectNodeId == "" || selectNodeId == "0") {
		message("请选择部件类型!");
		return;
	}
	var icon = getIconForSelectNode();
	$('body').css('cursor', 'url(' + icon + '),auto');
	map.setMapCursor('url(' + icon + '),auto');
	toolbar.activate(drawHandler.POINT);
	$(".cancelPartInMapBtn").attr("disabled", false);
	$(".addPartInMapBtn").attr("disabled", true);
});

function getIconForSelectNode() {
	var treeObj = $.fn.zTree.getZTreeObj("partTree");
	var icon = defaultPartIcon;
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode) {
			icon = selectNode.icon;
		}
	}
	return icon;
}

function getTreeIdForSelectNode() {
	var treeObj = $.fn.zTree.getZTreeObj("partTree");
	var id = "";
	var selectNodes = treeObj.getSelectedNodes(treeObj);
	if (selectNodes) {
		var selectNode = selectNodes[0];
		if (selectNode && selectNode.id != "0") {
			id = selectNode.id;
		}
	}
	return id;
}

(function() {
	var partType = ''
	$("#avatar").error(function() {
		$(this).attr("src", "../img/upload.png");
		$(this).error = null;
	});
	var image;
	$("body")
			.on(
					"change",
					"#file",
					function() {
						var $file = $(this);
						var fileObj = $file[0];
						var windowURL = window.URL || window.webkitURL;
						var dataURL;
						var $img = $("#avatar");

						if (fileObj && fileObj.files && fileObj.files[0]) {
							dataURL = windowURL
									.createObjectURL(fileObj.files[0]);
						} else {
							dataURL = $file.val();
							var imgObj = document.getElementById("preview");
							// 两个坑:
							// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
							// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
							imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
							imgObj.filters
									.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
						}

						// 限制上传图片像素大小
						image = new Image();
						image.src = dataURL;
						image.onload = function() {
							var height = image.height;
							var width = image.width;
							if (width > 30 && height > 30) {
								message('请上传30*30像素');
								$file.val("");
								return false;
							}
							$img.attr('src', dataURL);
						}
					});

	jQuery('#fileclick').on('click', function() {
		return $("#file").click();
	});

	// 添加菜单，弹出弹窗
	jQuery('.addBtn').on('click', function() {
		// jQuery('#id').val('');
		// jQuery('#partName').val('');
		// jQuery('#manufacturer').val('');
		// jQuery('#productionTime').val('');
		// jQuery('#installationTime').val('');
		// $("#state option:first").prop("selected", 'selected');
		// 清空表单
		var selectNodeId = getTreeIdForSelectNode();
		if (selectNodeId == "" || selectNodeId == "0") {
			message("请选择部件类型!");
			return;
		}
		jQuery('#id').val('');
		currentGraphic = null;

		$("#modalForm")[0].reset();
		$("#avatar").attr('src', '../img/upload.png');
		//jQuery('#Modal').modal('show');
		$("#Modal").modal({
			backdrop : 'static'
		});
	});

	// 返回按钮
	jQuery('.goBackBtn').on('click', function() {
		if ($("#id").val() == null || $("#id").val() == "") {
			map.graphics.remove(currentGraphic); // 将绘图从图层中移除
			currentGraphic = null;
		} else {

			var mapPoint = currentGraphic.geometry;
			mapPoint.setX(currentGraphic.attributes.longitude);
			mapPoint.setY(currentGraphic.attributes.latitude);
			currentGraphic.setGeometry(mapPoint);
		}
	});

	// 查询
	jQuery('.searchBtn').on('click', function() {
		serverData.key = jQuery('#search').val();
		serverTable.draw();
	})

	// 撤销查询
	jQuery('.resetBtn').on("click", function() {
		jQuery('#search').val('');
		serverData.key = '';
		serverTable.draw();
	});

	// 查询
	jQuery('.searchBtn1').on('click', function() {
		serverData1.key = jQuery('#search1').val();
		serverTable1.draw();
	})

	// 撤销查询
	jQuery('.resetBtn1').on("click", function() {
		jQuery('#search1').val('');
		serverData1.key = '';
		serverTable1.draw();
	});

	var primaryNode = [];
	function initPartTypeTree() {
		// 初始化 层级树
		var url = window.rootPath + '/ui/bindingpart/getAllNodes';
		jQuery.ajax({
			url : url,
			cache : false,
			type : "get",
			data : '',
			dataType : "json",
			contentType : 'application/json;charset=utf-8',// 解决返回数据中的中文乱码问题
			success : function(data) {
				primaryNode.push({
					id : 0,
					name : "部件层级",
					open : "true",
					icon : defaultPartIcon
				// iconSkin:"diy03"
				});
				for (var i = 0; i < data.nodes.length; i++) {
					if (data.nodes[i].icon != undefined
							&& data.nodes[i].icon != "") {
					} else {
						data.nodes[i].icon = defaultPartIcon;
					}
					primaryNode.push(data.nodes[i]);
				}
				$.fn.zTree.init($("#partTree"), modalSetting, primaryNode);
			}
		});
	}
	;
	// 设置tree图标大小
	function zTreeOnNodeCreated(event, treeId, treeNode) {
		if (treeNode.type != "folder") {
			$('#' + treeNode.tId + '_ico').css(
					"background",
					"url('" + treeNode.icon
							+ "') center center/16px 16px no-repeat");
		}
	}
	// //////////////初始化模型的树结构/////////////////////////
	var modalSetting = {
		edit : {
			enable : false,
			showRemoveBtn : false,
			showRenameBtn : false,
		},
		data : {
			simpleData : {
				enable : true,
				idKey : "id",
				pIdKey : "parentId",
				rootParentId : 0
			}
		},
		view : {
			showLine : true,
			showIcon : true
		},
		check : {
			enable : false,
			chkStyle : "radio",
			radioType : "level"
		},
		callback : {
			onNodeCreated : zTreeOnNodeCreated,
			onClick : getPartBaseInfo
		}

	};
	function getPartBaseInfo(e, treeId, treeNode) {
		var Id = treeNode.id;
		currentGraphic = null;
		if (Id == undefined || '0' == Id) {
			return;
		}

		partType = treeNode.partType;
		if (partType == '1') {
			jQuery('#interfaceDiv').show();
		} else {
			jQuery('#interfaceDiv').hide();
		}
		serverData.partId = Id;
		serverTable.draw();

		$.ajax({
			url : rootPath + "/ui/partBaseInfo/getpartsbyparttype?parttypeid="
					+ Id,
			dataType : 'json',
			type : 'get',
			contentType : "application/json",
			success : function(result) {
				if (result.code <= 0) {
					message("获取部件失败!");
				} else {
					if (result.data) {
						map.graphics.clear();
						var symbolurl = getIconForSelectNode();
						for (var i = 0; i < result.data.length; i++) {
							var temp=createPoint(result.data[i], symbolurl)
							//设置部位为地图中心
//							if(i==0){
//								map.centerAndZoom(temp.geometry, map.getLevel());
//							}
						}
					}
				}
			}
		});
	};
	
	function deletePotin(id){
		var graphics = map.graphics.graphics;
		var obj;
		if(graphics != null){
			for (var i = 0; i < graphics.length; i++) {
				if (graphics[i]) {
					if (graphics[i].attributes) {
						if (graphics[i].attributes.id == id) {
							obj = graphics[i];
							break;
						}
					}
				}
			}
		}
		map.graphics.remove(obj);
	}
	function createPoint(data, symbolurl) {
		var symbol = new esri.symbol.PictureMarkerSymbol({
			"url" : symbolurl, // 图标路径
			"width" : 20, // 图标的宽度
			"height" : 20
		// 图标的高度
		});

		var myPoint = {
			"geometry" : {
				"type" : "point",
				"x" : data.longitude,
				"y" : data.latitude,
				"spatialReference" : {
					"wkid" : 4326
				}
			},
			"attributes" : data,
			"symbol" : symbol
		/*
		 * , "infoTemplate": { "title": "sssss", "content": "latude:${Field}" }
		 */
		};
		var geometry = {
			"type" : "point",
			"x" : data.longitude,
			"y" : data.latitude,
			"spatialReference" : {
				"wkid" : 4326
			}
		};

		var graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.attributes = data;
		map.graphics.add(graphic);
		return graphic;
	}

	function cleanData() {
		jQuery('#conditionId').val('');
		jQuery('#conditionType').val('');
		jQuery('#content').val('');
	}

	function setData(data) {
		jQuery('#conditionId').val(data.id);
		jQuery('#conditionType').val(data.conditionType.id);
		jQuery('#content').val(data.content);
	}

	function addDisabled() {
		jQuery('#conditionType').attr('disabled', true);
		jQuery('#content').attr('disabled', true);
	}

	function removeDisabled() {
		jQuery('#conditionType').removeAttr("disabled");
		jQuery('#content').removeAttr("disabled");
	}

	function setButtonShow(addInfoBtn, editInfoBtn, saveInfoBtn) {
		if (addInfoBtn) {
			jQuery('.addInfoBtn').removeAttr('disabled');
		} else {
			jQuery('.addInfoBtn').attr('disabled', true);
		}
		if (editInfoBtn) {
			jQuery('.editInfoBtn').removeAttr('disabled');
		} else {
			jQuery('.editInfoBtn').attr('disabled', true);
		}
		if (saveInfoBtn) {
			jQuery('.saveInfoBtn').removeAttr('disabled');
		} else {
			jQuery('.saveInfoBtn').attr('disabled', true);
		}
	}

	// table数据显示
	var serverData = {};
	var serverTable;

	// table数据显示
	var serverData1 = {};
	serverData1.partId = '';
	var serverTable1;
	jQuery(document)
			.ready(
					function() {
						initPartTypeTree();
						serverTable = jQuery('#dataTable')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "post",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/bindingpart/getpagebypart',// '/ui/partBaseInfo/getpage',
												"data" : function(d) {
													return $.extend({}, d,
															serverData);
												}
											},
											columns : [
													{
														data : null,
														defaultContent : ""
													},
													{
														data : 'partName'
													},
													{
														data : 'manufacturer'
													},
													{
														data : 'productionTime',
														render : function(data,
																type, full,
																meta) {
															if (data)
																return moment(
																		data)
																		.format(
																				'YYYY/MM/DD');
															else
																return '';
														}
													},
													{
														data : 'installationTime',
														render : function(data,
																type, full,
																meta) {
															if (data)
																return moment(
																		data)
																		.format(
																				'YYYY/MM/DD');
															else
																return '';
														}
													},
													{
														data : 'iconAddress',
														render : function(data,
																type, full,
																meta) {
															if (data
																	&& data != '') {
																var iconAddress = window.rootPath
																		+ '/'
																		+ data;
																var operate = '<img src="'
																		+ iconAddress
																		+ '" width="30px" height="30px"/>';
																return operate;
															} else {
																return '';
															}
														}
													},
													{
														data : 'hierarchy',
														render : function(data,
																type, full,
																meta) {
															if (data)
																return data.groupName;
															else
																return '';
														}
													},
													{
														data : 'part.partName'
													},
													{
														data : 'state.title'
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
																	+ '<button type="button" class="btn btn-sm btn-info delBtn" title="删除"><i class="fa fa-remove"></i></button>';

															return operate;

														}
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;

												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}
												serverTable1.draw(false);
												serverTable.off('click', 'tr');
												serverTable
														.on(
																'click',
																'tr',
																function(event) {
																	event = event
																			|| window.event;
																	var target = event.target
																			|| event.scrElement;
																	var data = serverTable
																			.row(
																					this)
																			.data();

																	if (target.className
																			.indexOf('fa-remove') != -1
																			|| target.className
																					.indexOf('delBtn') != -1) {

																		deleteInfo(data);
																	}

																	if (target.className
																			.indexOf('fa-pencil') != -1
																			|| target.className
																					.indexOf('editBtn') != -1) {

																		editInfo(data);
																	}

																	if ($(this)
																			.hasClass(
																					'selected')) {
																		$(this)
																				.removeClass(
																						'selected');
																		serverData1.partId = "";
																	} else {
																		serverTable
																				.$(
																						'tr.selected')
																				.removeClass(
																						'selected');
																		$(this)
																				.addClass(
																						'selected');
																		// 获取当前行数据
																		serverData1.partId = data.id;
																	}
																	serverTable1
																			.draw(false);
																	cleanData();
																	removeDisabled();
																	setButtonShow(
																			true,
																			false,
																			true);
																	return;
																});
											}
										});

						serverTable1 = jQuery('#dataTable1')
								.DataTable(
										{
											"serverSide" : true,
											"ordering" : false,
											"ajax" : {
												"dataType" : "json",
												"type" : "post",
												"cache" : false,
												"url" : window.rootPath
														+ '/ui/partBaseInfo/getConditionPage',// '/ui/partBaseInfo/getpage',
												"data" : function(d) {
													return $.extend({}, d,
															serverData1);
												}
											},
											columns : [
													{
														data : null,
														defaultContent : ""
													},
													{
														data : 'id',
														render : function(data,
																type, full,
																meta) {
															var operate = '<input type="checkbox" dataId="'
																	+ data
																	+ '" group="removeDate"/>';
															return operate;
														}
													},
													{
														data : 'conditionType.title'
													},
													{
														data : 'content'
													},
													{
														data : null,
														defaultContent : "",
														render : function(data,
																type, full,
																meta) {
															var operate = '<button type="button" class="btn btn-sm btn-info delConBtn" title="删除"><i class="fa fa-remove"></i></button>';

															return operate;

														}
													} ],
											"drawCallback" : function(oSettings) {
												var k = 0;
												var total = oSettings.aiDisplay.length
														+ oSettings._iDisplayStart;

												for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
													$(
															'td:eq(0)',
															oSettings.aoData[oSettings.aiDisplay[k]].nTr)
															.text(i + 1);
													k++;
												}

												cleanData();
												removeDisabled();
												setButtonShow(true, false, true);

												serverTable1.off('click', 'tr');
												serverTable1
														.on(
																'click',
																'tr',
																function(event) {
																	event = event
																			|| window.event;
																	var target = event.target
																			|| event.scrElement;
																	var data = serverTable1
																			.row(
																					this)
																			.data();
																	if (target.className
																			.indexOf('fa-remove') != -1
																			|| target.className
																					.indexOf('delConBtn') != -1) {
																		deleteConInfo(data);
																	}

																	if ($(this)
																			.hasClass(
																					'selected')) {
																		$(this)
																				.removeClass(
																						'selected');
																		cleanData();
																		removeDisabled();
																		setButtonShow(
																				true,
																				false,
																				true);
																	} else {
																		serverTable1
																				.$(
																						'tr.selected')
																				.removeClass(
																						'selected');
																		$(this)
																				.addClass(
																						'selected');
																		setData(data);
																		addDisabled();
																		setButtonShow(
																				true,
																				true,
																				false);
																	}

																});
											}
										});

						var deleteConInfo = function(data) {
							if (!data)
								return;
							$
									.springLemonDialog({
										content : '确认删除？',// 确认文本
										clickButton : function(sender, modal,
												index) {// 按钮事件处理
											// index:0 确认 1：取消
											// sender:事件源
											// 如按钮，sender.html()可得到按钮文字如：取消
											if (index == 0) {
												var url = window.rootPath
														+ "/ui/partBaseInfo/deleteCondition/"
														+ data.id;
												jQuery.ajax({
													url : encodeURI(url),
													cache : false,
													type : "post",
													dataType : "json",
													success : function(result) {
														serverTable1.draw(false);
														message(result.msg);
													}
												});
											}
											$(this).closeDialog(modal);
										}

									});

						};

						var deleteInfo = function(data) {
							if (!data)
								return;
							$.springLemonDialog({
								content : '确认部件：' + data.partName + '？',// 确认文本
								clickButton : function(sender, modal, index) {// 按钮事件处理
									// index:0 确认 1：取消
									// sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
									if (index == 0) {
										var url = window.rootPath
												+ "/ui/partBaseInfo/delete/"
												+ data.id;
										$("#right").mLoading("show");
										jQuery.ajax({
											url : encodeURI(url),
											cache : false,
											type : "post",
											dataType : "json",
											success : function(result) {
												serverTable.draw(false);
												deletePotin(data.id);
												message(result.msg);
												$("#right").mLoading("hide");
											}
										});
									}
									$(this).closeDialog(modal);
								}

							});

						};
						// 编辑信息
						var editInfo = function(data) {
							if (!data)
								return;
							var graphics = map.graphics.graphics;
							for (var i = 0; i < graphics.length; i++) {
								if (graphics[i]) {
									if (graphics[i].attributes) {
										if (graphics[i].attributes.id == data.id) {
											currentGraphic = graphics[i];
											console
													.log(graphics[i].attributes.id);
											break;
										}
									}
								}
							}
							editPartFromMap(data, data.longitude, data.latitude);
							/*
							 * jQuery('#longitude').val(data.longitude);
							 * jQuery('#latitude').val(data.latitude);
							 * jQuery('#id').val(data.id);
							 * jQuery('#partName').val(data.partName);
							 * jQuery('#manufacturer').val(data.manufacturer);
							 * jQuery('#productionTime').val(
							 * moment(data.productionTime).format(
							 * 'YYYY-MM-DD')); jQuery('#installationTime').val(
							 * moment(data.installationTime).format(
							 * 'YYYY-MM-DD'));
							 * jQuery('#state').val(data.state.id); var
							 * iconAddress = data.iconAddress; if (typeof
							 * (iconAddress) != 'undefined' && iconAddress !=
							 * '') { iconAddress = window.rootPath + '/' +
							 * iconAddress; } else { iconAddress =
							 * '../img/upload.png'; } $("#avatar").attr('src',
							 * iconAddress); jQuery('#Modal').modal('show');
							 */
						};

						// 新增，编辑保存
						jQuery('.saveBtn')
								.on(
										'click',
										function() {
											if (jQuery("#modalForm")
													&& !jQuery("#modalForm")
															.Validform(
																	{
																		tiptype : 3,
																		showAllError : true
																	}).check(
																	false)) {
												return;
											}
											;
											if (partType == '1') {
												if (jQuery("#interfaceForm")
														&& !jQuery(
																"#interfaceForm")
																.Validform(
																		{
																			tiptype : 3,
																			showAllError : true
																		})
																.check(false)) {
													return;
												}
												;
											}

											var url = window.rootPath
													+ '/ui/partBaseInfo/savePartBaseInfoWithFile';
											var id = $('#id').val();

											var partName = $('#partName').val();
											var manufacturer = $(
													'#manufacturer').val();
											var productionTime = $(
													'#productionTime').val();
											var installationTime = $(
													'#installationTime').val();
											var longitude = $("#longitude")
													.val();
											var latitude = $("#latitude").val();
											var stateId = $("#state").val();

											var deviceIdentify = $(
													"#deviceIdentify").val();
											var interfaceAddress = $(
													"#interfaceAddress").val();
											var interfacePort = $(
													"#interfacePort").val();
											var partAdress = $('#partAdress').val();
											var data = {
												"id" : id,
												"partName" : partName,
												"manufacturer" : manufacturer,
												"production" : productionTime,
												"installation" : installationTime,
												"longitude" : longitude,
												"latitude" : latitude,
												"state" : stateId,
												"part" : getTreeIdForSelectNode(),
												"deviceIdentify" : deviceIdentify,
												"interfaceAddress" : interfaceAddress,
												"interfacePort" : interfacePort,
												"partAdress" : partAdress,
											}
											$("#right").mLoading("showNoIcon");
											$
													.ajaxFileUpload({
														url : url,
														secureuri : false,// 是否需要安全协议
														fileElementId : [ "file" ],// 文件上传的Id属性
														dataType : 'text',
														data : data,
														success : function(
																result, status) {
															var start = result
																	.indexOf("{");
															var end = result
																	.indexOf("</pre>");
															var jsonStr = result
																	.substring(
																			start,
																			end);
															var temp = JSON
																	.parse(jsonStr);
															if (temp.code == '1') {
																if (!currentGraphic) {
																	var symbolurl = getIconForSelectNode();
																	currentGraphic = createPoint(
																			temp.attributes,
																			symbolurl);
																}
																currentGraphic.attributes = temp.attributes;
																if (currentGraphic.geometry.x != currentGraphic.attributes.longitude
																		|| currentGraphic.geometry.y != currentGraphic.attributes.latitude) {
																	var mapPoint = currentGraphic.geometry;
																	mapPoint
																			.setX(currentGraphic.attributes.longitude);
																	mapPoint
																			.setY(currentGraphic.attributes.latitude);
																	currentGraphic
																			.setGeometry(mapPoint);
																}
															}
															message(temp.msg);
															jQuery('#Modal').modal('hide');
															serverTable.draw(false);
															$("#right").mLoading("hide");
														}
													});

										});

					});

	jQuery('.saveInfoBtn').on('click', function() {
		if (serverData1.partId == '') {
			message('请选择部件信息！');
			return;
		}
		if (jQuery("#conditionForm") && !jQuery("#conditionForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		}
		;
		var url = window.rootPath + '/ui/partBaseInfo/saveCondition';

		var d = {
			"id" : jQuery('#conditionId').val(),
			"part" : serverData1.partId,
			"conditionType" : jQuery('#conditionType').val(),
			"content" : jQuery('#content').val()
		}
		$("#right").mLoading("show");
		jQuery.ajax({
			url : encodeURI(url),
			type : "post",
			data : JSON.stringify(d),
			dataType : "json",
			contentType : "application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
			success : function(data) {
				cleanData();
				setButtonShow(true, false, true);
				serverTable1.draw(false);
				message(data.msg);
				$("#right").mLoading("hide");
			}
		});
	});
	var graphicArrays = [];
	// 地图上面快捷查询
	jQuery('.searchMapBtn')
			.on(
					'click',
					function() {
						graphicArrays = getcurrentGraphicsByValue($(
								"#searchMap").val());
						for (var i = 0; i < graphicArrays.length; i++) {
							if (i == 0) {
								map.centerAndZoom(graphicArrays[i].geometry
										, map.getLevel());
							}
							var symbol = graphicArrays[i].symbol;
							symbol.height = symbol.height + extendScal;
							symbol.width = symbol.width + extendScal;
							graphicArrays[i].setSymbol(symbol);
						}
					});
	jQuery('.resetMapBtn').on('click', function() {
		jQuery('#searchMap').val('');

		if (graphicArrays) {
			for (var i = 0; i < graphicArrays.length; i++) {
				var symbol = graphicArrays[i].symbol;
				symbol.height = symbol.height - extendScal;
				symbol.width = symbol.width - extendScal;
				graphicArrays[i].setSymbol(symbol);
			}
			graphicArrays = null;
		}
	});
	function getcurrentGraphicsByValue(txt) {
		var graphicArray = [];
		if(txt==undefined||txt==""){
			return graphicArray;
		}
		var graphics = map.graphics.graphics;
		for (var i = 0; i < graphics.length; i++) {
			if (graphics[i] && graphics[i].geometry.type == "point") {
				if (graphics[i].attributes) {
					if (graphics[i].attributes.partName
							&& graphics[i].attributes.partName.indexOf(txt) != -1) {
						graphicArray.push(graphics[i]);
						continue;
					} else if (graphics[i].attributes.partIdentify
							&& graphics[i].attributes.partIdentify.indexOf(txt) != -1) {
						graphicArray.push(graphics[i]);
						continue;
					} else if (graphics[i].attributes.manufacturer
							&& graphics[i].attributes.manufacturer.indexOf(txt) != -1) {
						graphicArray.push(graphics[i]);
						continue;
					} else if (graphics[i].attributes.deviceIdentify
							&& graphics[i].attributes.deviceIdentify
									.indexOf(txt) != -1) {
						graphicArray.push(graphics[i]);
						continue;
					} else if (graphics[i].attributes.hierarchy
							&& graphics[i].attributes.hierarchy.groupName
									.indexOf(txt) != -1) {
						graphicArray.push(graphics[i]);
						continue;
					}
				}
			}
		}
		return graphicArray;
	}
	;

	jQuery('.addInfoBtn').on('click', function() {
		cleanData();
		removeDisabled();
		setButtonShow(true, false, true);
	})

	jQuery('.editInfoBtn').on('click', function() {
		removeDisabled();
		setButtonShow(true, false, true);
	})

	// 已绑定 全选
	$("#allBound").click(function() {
		var removeDate = $(":checkbox[group=removeDate]");
		if ($(this).prop("checked")) {
			removeDate.each(function() {
				$(this).prop("checked", true);
			});
		} else {
			removeDate.each(function() {
				$(this).prop("checked", false);
			});
		}
	});

	// 获取全选数据
	function getSelectData(group) {
		var obj = $(":checkbox[group=" + group + "]:checked");
		var myArray = new Array();
		var i = 0;
		obj.each(function() {
			myArray[i++] = $(this).attr('dataId');
		});
		return myArray;
	}

	// 移除全部信息
	jQuery('.deleteBtn').on(
			'click',
			function() {
				var dataInfo = getSelectData('removeDate');
				if (dataInfo.length == 0) {
					message('请选择需要移除的条件信息!');
					return;
				}
				$.springLemonDialog({
					content : '移除所有条件信息？',// 确认文本
					clickButton : function(sender, modal, index) {// 按钮事件处理
						// index:0 确认 1：取消
						// sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
						if (index == 0) {
							$("#right").mLoading("show");
							var d = {
								"dataInfo" : dataInfo
							};

							var url = window.rootPath
									+ '/ui/partBaseInfo/removeConditionAll';
							jQuery.ajax({
								url : encodeURI(url),
								cache : false,
								type : "post",
								data : JSON.stringify(d),
								dataType : "json",
								contentType : "application/json;charset=utf-8",// 解决返回数据中的中文乱码问题
								success : function(data) {
									message(data.msg);
									$("#allBound").prop("checked", false);
									serverTable1.draw(false);
									$("#right").mLoading("hide");
								}
							});
						}
						$(this).closeDialog(modal);
					}

				});
			});
	
})();
function setPartLocation(lat,lng){
	var bd = wgs2bd(lat,lng);
	var pt = new BMap.Point(bd[1], bd[0]);
	// 创建一个地理位置解析器
	var geoc = new BMap.Geocoder();
	geoc.getLocation(pt,
		function(rs) {// 解析格式：城市，区县，街道
			var addComp = rs.addressComponents;
			jQuery("#partAdress").val(addComp.province + ", " + addComp.city + ", "
				+ addComp.district + ", " + addComp.street + ", "
				+ addComp.streetNumber);
		});
}